package com.leo.foodmaster.admin.system.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.foodmaster.admin.system.entity.SysUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

/**
 * <p>
 * 用户表 Mapper 接口
 * </p>
 *
 * @author Leo
 * @since 2021-06-17
 */
@Repository
public interface UserMapper extends BaseMapper<SysUser> {

    /**
     * 分页条件查询用户列表
     * @param page 分页参数
     * @param account 用户名称
     * @param phone 手机号码
     * @param status 用户状态
     * @param beginTime 开始时间
     * @param endTime 结束时间
     * @param organId 机构Id
     * @param deptId 部门Id
     * @return IPage<User>
     */
    @Select("<script>" +
            "SELECT a.* " +
            "FROM sys_user AS a " +
            "JOIN " +
            "(SELECT id FROM sys_organ " +
            "WHERE 1 =1 " +

            "<if test='organId != null and organId != 1 '>" +
            "AND id = #{organId} OR organ_id = #{organId} " +
            "</if>" +

            "<if test='organId == 1 '>" +
            "AND id = 1 " +
            "</if>" +

            ") AS b " +
            "ON a.organ_id = b.id " +
            "WHERE a.del_flag = 0 " +

            "<if test='deptId != null '>" +
            "AND a.dept_id = #{deptId} " +
            "</if>" +

            "<if test='account != null and account.trim() != &quot;&quot; '>" +
            "AND a.account like CONCAT('%', #{account}, '%') " +
            "</if>" +

            "<if test='phone != null and phone.trim() != &quot;&quot; '>" +
            "AND a.phone like CONCAT('%', #{phone}, '%') " +
            "</if>" +

            "<if test='status != null '>" +
            "AND a.status = #{status} " +
            "</if>" +

            "<if test='beginTime != null and beginTime.trim() != &quot;&quot; '>" +
            "AND a.create_time &gt;= #{beginTime} " +
            "</if>" +

            "<if test='endTime != null and endTime.trim() != &quot;&quot; '>" +
            "AND a.create_time &lt;= #{endTime} " +
            "</if>" +

            "ORDER BY a.create_time DESC " +
            "</script>")
    IPage<SysUser> getUserPageList(Page<SysUser> page, String account, String phone,
                                Integer status, String beginTime, String endTime, Long organId, Long deptId);

    /**
     * 根据用户Id查询对应的公司状态
     * @param userId 用户Id
     * @return String
     */
    @Select("SELECT b.`status` " +
            "FROM sys_user AS a " +
            "JOIN sys_organ AS b " +
            "ON a.organ_id = b.id " +
            "WHERE a.id = #{userId} ")
    String getOrganStatus(Long userId);
}
